<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form
      size="small"
      :inline="true"
      @submit.native.prevent
      label-width="70px"
    >
      <el-form-item label="设备编号">
        <el-input
          v-model="searchForm.deviceCode"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleSearch"
        />
      </el-form-item>
      <el-form-item label="设备名称">
        <el-input
          v-model="searchForm.deviceName"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleSearch"
        />
      </el-form-item>
      <el-form-item label="线别名称">
        <el-input
          v-model="searchForm.lineId"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleSearch"
        />
      </el-form-item>
      <el-form-item label="工号">
        <el-input
          v-model="searchForm.user"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleSearch"
        />
      </el-form-item>
      <el-form-item label="姓名">
        <el-input
          v-model="searchForm.userName"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleSearch"
        />
      </el-form-item>
      <el-form-item label="所属课别">
        <el-input
          v-model="searchForm.deptName"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleSearch"
        />
      </el-form-item>
      <el-form-item label="区分">
        <el-select
          v-model="searchForm.type"
          placeholder="请选择"
          filterable
          clearable
        >
          <el-option
            v-for="item in types"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleSearch"
          class="button"
          plain
          >查询</el-button
        >
        <el-button
          type="info"
          icon="el-icon-refresh"
          size="mini"
          @click="handleReset"
          class="button"
          plain
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          @click="handleAdd"
          class="button"
          plain
          v-hasPermi="['deviceBind_add']"
          >添加</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          size="mini"
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['deviceBind_delete']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          @click="handleImport()"
          v-hasPermi="['deviceBind_upload']"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="mini"
          @click="handleExport()"
          v-hasPermi="['deviceBind_Export']"
          >导出</el-button
        >
      </el-col>
    </el-row>
    <!-- 表格数据 -->
    <el-table
      ref="refTable"
      v-loading="loading"
      :data="tableList"
      border
      :max-height="THeight"
      @selection-change="handleSelectionChange"
      @close="cancel"
    >
      <el-table-column type="selection" width="50" align="center" fixed />
      <el-table-column label="序号" width="50" align="center" prop="Index" />
      <el-table-column label="设备编号" align="center" prop="deviceCode" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="单元号" align="center" prop="unitNo" />
      <el-table-column label="线别名称" align="center" prop="lineId" />
      <el-table-column label="所属课别" align="center" prop="dept" />
      <el-table-column label="工号" align="center" prop="user" />
      <el-table-column label="姓名" align="center" prop="userName" />
      <el-table-column label="所属部门" align="center" prop="userDept" />
      <el-table-column label="区分" align="center" prop="type" />
      <el-table-column label="权限" align="center" prop="permissions" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['deviceBind_edit']"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['deviceBind_delete']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <pagination
      :total="total"
      :page.sync="Page.pageNum"
      :limit.sync="Page.pageSize"
      @pagination="getInfo()"
    />
    <!-- 对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="380px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-card>
        <el-form ref="form" :model="form" label-width="85px" :rules="rules">
          <el-form-item label="设备编号" prop="deviceCode">
            <el-select
              v-model="form.deviceCode"
              placeholder="请选择"
              filterable
              :disabled="title == '修改数据'"
            >
              <el-option
                v-for="item in deviceNos"
                :key="item.value"
                :label="item.label1"
                :value="item.value"
              >
                <span style="float: left">{{ item.label1 }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.label2
                }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备名称" prop="deviceName">
            <el-input
              v-model="form.deviceName"
              placeholder="请输入"
              style="width: 217px"
            />
          </el-form-item>
          <el-form-item label="线别名称" prop="lineId">
            <el-input
              v-model="form.lineId"
              placeholder="请输入"
              style="width: 217px"
            />
          </el-form-item>
          <el-form-item label="所属课别" prop="dept">
            <el-input
              v-model="form.dept"
              placeholder="请输入"
              style="width: 217px"
            />
          </el-form-item>
          <el-form-item label="工号" prop="user">
            <el-input
              v-model="form.user"
              placeholder="请输入"
              :disabled="title == '修改数据'"
              style="width: 217px"
            />
          </el-form-item>
          <el-form-item label="姓名" prop="userName">
            <el-input
              v-model="form.userName"
              placeholder="请输入"
              style="width: 217px"
            />
          </el-form-item>
          <el-form-item label="所属部门" prop="userDept">
            <el-input
              v-model="form.userDept"
              placeholder="请输入"
              style="width: 217px"
            />
          </el-form-item>
          <el-form-item label="区分" prop="type">
            <el-select
              v-model="form.type"
              placeholder="请选择"
              filterable
              clearable
            >
              <el-option
                v-for="item in types"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="权限">
            <el-select
              v-model="permissions"
              clearable
              placeholder="请选择"
              multiple
            >
              <el-option
                v-for="(item, index) in Permissions"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 文件导入 -->
    <UploadExcel
      ref="child"
      moban="deviceBind"
      :relations="relations"
      @child-event="ImportFile"
    ></UploadExcel>
  </div>
</template>

<script>
import moment from "moment";
import XLSX from "xlsx";
import {
  reqGetDev,
  reqGetDevUser,
  reqInsertDevUser,
  reqDeleteDevUser,
  reqUpdateDevUser,
} from "@/api/newApi/OCAP/index.js";

export default {
  components: {
    UploadExcel: () => import("@/views/components/uploadExcel"),
  },
  data() {
    return {
      THeight: undefined,
      loading: false,
      tableList: [],
      open: false,
      title: "",
      total: 0,
      // 表单参数
      form: {},
      permissions: ["查看"],
      // 查询参数
      searchForm: {},
      Page: { pageNum: 1, pageSize: 20 },
      // 非多个禁用
      multiple: true,
      rules: {
        deviceCode: {
          required: true,
          message: "设备编号必填",
          trigger: "blur",
        },
        user: { required: true, message: "工号必填", trigger: "blur" },
        permissions: { required: true, message: "权限必填", trigger: "blur" },
      },
      ids: [],
      Indexs: [],
      Permissions: ["查看", "解锁"],
      deviceNos: [],
      selection1: [],
      fileList: [], //上传文件
      relations: {
        设备编号: "deviceCode",
        设备名称: "deviceName",
        单元号: "unitNo",
        线别名称: "lineId",
        所属课别: "dept",
        工号: "user",
        姓名: "userName",
        所属部门: "userDept",
        区分: "type",
        权限: "permissions",
      },
      //区分
      types: [
        {
          value: "FPC",
          label: "FPC",
        },
        {
          value: "SMT",
          label: "SMT",
        },
      ],
    };
  },
  computed: {},
  mounted() {
    this.THeight = (72 * window.innerHeight) / 100;
    this.getDev();
    this.getInfo();
  },
  methods: {
    //给数据加id,Index
    addIdIndex(resData) {
      this.tableList = resData.map((item, index) => {
        return {
          Index: (this.Page.pageNum - 1) * this.Page.pageSize + index + 1,
          ...item,
        };
      });
    },
    //获取设备编号下拉框
    async getDev() {
      let res = await reqGetDev({ user: null });
      if (res.code == 0) {
        this.deviceNos = res.data;
        this.deviceNos.forEach((item) => {
          item.label1 = item.deviceCode;
          item.label2 = item.unitNo;
          item.value = `${item.deviceCode}拼接${item.unitNo}`;
        });
      } else {
        this.$modal.msgError(res.message);
      }
    },
    //获取数据
    async getInfo() {
      //前后去空格
      if (this.searchForm.deviceCode) {
        this.searchForm.deviceCode = this.searchForm.deviceCode.trim();
      }
      if (this.searchForm.user) {
        this.searchForm.user = this.searchForm.user.trim();
      }
      this.loading = true;
      let res = await reqGetDevUser(Object.assign(this.searchForm, this.Page));
      if (res.code == 0) {
        this.addIdIndex(res.data);
        this.total = res.total;
      } else {
        this.$modal.msgError(res.message);
      }
      this.loading = false;
    },
    /** 搜索按钮操作 */
    handleSearch() {
      this.Page.pageNum = 1;
      this.getInfo();
    },
    // 重置
    handleReset() {
      this.searchForm = {};
      this.Page.pageNum = 1;
      this.getInfo();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = {
        deviceCode: row.deviceCode,
        deviceName: row.deviceName,
        unitNo: row.unitNo,
        lineId: row.lineId,
        dept: row.dept,
        user: row.user,
        userName: row.userName,
        userDept: row.userDept,
        devUserId: row.devUserId,
        type: row.type,
      };
      if (row.permissions != "") {
        this.permissions =
          row.permissions.split(",").length == 1
            ? [row.permissions.split(",")[0]]
            : [row.permissions.split(",")[0], row.permissions.split(",")[1]];
      } else {
        this.permissions = null;
      }
      this.open = true;
      this.title = "修改数据";
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        let reqForm = {};
        if (valid) {
          //添加
          if (this.title == "添加数据") {
            reqForm = {
              ...this.form,
              deviceCode: this.form.deviceCode.split("拼接")[0],
              unitNo: this.form.deviceCode.split("拼接")[1],
              user: this.form.user,
              permissions: this.permissions.toString(),
            };
            reqInsertDevUser(reqForm).then((res) => {
              if (res.code == 0) {
                this.$modal.msgSuccess("添加成功");
                this.open = false;
                this.getInfo();
              } else {
                this.$modal.msgError(res.msg);
              }
            });
          } else {
            // 修改
            reqForm = {
              ...this.form,
              devUserId: this.form.devUserId,
              permissions: this.permissions.toString(),
            };
            reqUpdateDevUser(reqForm).then((res) => {
              if (res.code == 0) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getInfo();
              } else {
                this.$modal.msgError(res.message);
              }
            });
          }
        }
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection1 = selection;
      this.ids = selection.map((item) => item.devUserId);
      this.Indexs = selection.map((item) => item.Index).sort((a, b) => a - b);
      this.multiple = !selection.length;
    },
    //删
    handleDelete(row) {
      let delArr = [];
      if (row) {
        delArr = [{ devUserId: row.devUserId }];
      } else {
        for (let i = 0; i < this.selection1.length; i++) {
          delArr.push({
            devUserId: this.selection1[i].devUserId,
          });
        }
      }
      this.$modal
        .confirm('是否确认删除序号为"' + this.Indexs + '"的数据项？')
        .then(function () {
          return reqDeleteDevUser(delArr);
        })
        .then((res) => {
          if (res.code == 0) {
            this.$modal.msgSuccess("删除成功");
            if (this.tableList.length == 1 && this.searchForm.pageNum > 1) {
              this.searchForm.pageNum--;
            }
            this.getInfo();
            this.cancel();
          } else {
            this.$modal.msgError(res.msg);
          }
        })
        .catch(() => {});
    },
    // 表单重置
    reset() {
      this.form = {};
      this.permissions = ["查看"];
      this.resetForm("form");
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    //导入
    handleImport() {
      this.$refs.child.dialogOpen();
    },
    ImportFile(reqArr, fileItem) {
      // 将reqArr数组中每个对象的属性的属性值都改为字符串类型;
      for (let i = 0; i < reqArr.length; i++) {
        for (let key in reqArr[i]) {
          if (reqArr[i][key] !== null) {
            reqArr[i][key] = reqArr[i][key].toString();
          }
        }
      }
      Promise.all(reqArr.map((req) => reqInsertDevUser(req)))
        .then((responses) => {
          const success = responses.every((response) => response.code === 0);
          const has0 = responses.some((response) => response.code === 0);
          if (success) {
            this.$modal.msgSuccess("导入成功");
            this.$refs.child.uploadCancel();
            this.getInfo();
          } else {
            let indexArr1 = [];
            let indexArr2 = [];
            responses.forEach((item, index) => {
              if (item.code != 0 && item.msg == "该设备已经绑定了该工号") {
                indexArr1.push(index + 2);
              }
              if (item.code != 0 && item.msg == "该工号不存在") {
                indexArr2.push(index + 2);
              }
            });
            let Msg = "";
            if (indexArr1.length > 0) {
              Msg = `第${indexArr1.toString()}行设备已经绑定了对应工号，请勿重复添加;`;
            }
            if (indexArr2.length > 0) {
              Msg += `第${indexArr2.toString()}行工号不存在，无法添加;`;
            }
            if (has0) {
              Msg += "(其他行已成功添加)";
            }
            let spanText = Msg.split(";").map(
              (item) => `<span style='margin:10px;'>${item}</span><br/>`
            );
            this.$message({
              dangerouslyUseHTMLString: true,
              message: `<div style='overflow: auto;max-height: 70vh'>
          ${spanText.join("")}
            </div>`,
              type: "error",
            });
            this.getInfo();
          }
        })
        .catch((error) => {
          this.$modal.msgError("导入失败: " + error.message);
        });
    },
    //导出
    async handleExport() {
      if (this.tableList.length > 0) {
        const loading = this.$loading({
          lock: true,
          text: `Loading`,
          spinner: "el-icon-loading",
        });
        try {
          const headers = [
            "设备编号",
            "设备名称",
            "单元号",
            "线别名称",
            "所属课别",
            "工号",
            "姓名",
            "所属部门",
            "区分",
            "权限",
          ];
          //前后去空格
          if (this.searchForm.deviceCode) {
            this.searchForm.deviceCode = this.searchForm.deviceCode.trim();
          }
          if (this.searchForm.user) {
            this.searchForm.user = this.searchForm.user.trim();
          }
          let Page = { pageSize: this.total, pageNum: 1 };
          let res = await reqGetDevUser(Object.assign(this.searchForm, Page));
          const datas = res.data.map((item) => [
            item.deviceCode,
            item.deviceName,
            item.unitNo,
            item.lineId,
            item.dept,
            item.user,
            item.userName,
            item.userDept,
            item.type,
            item.permissions,
          ]);
          const worksheet = XLSX.utils.aoa_to_sheet([headers, ...datas]);
          const workbook = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(workbook, worksheet, "sheet1");
          XLSX.writeFile(
            workbook,
            `设备绑定${moment(new Date()).format("yyyy-MM-DD HH:mm")}.xlsx`
          );
        } catch (error) {
          console.error("导出数据失败:", error);
        } finally {
          loading.close();
        }
      } else {
        this.$modal.msgError("暂无数据可导出");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
//表头颜色
::v-deep .el-table .el-table__header-wrapper th,
.el-table .el-table__fixed-header-wrapper th {
  background-color: #f0f8ff !important;
}
//dialog
::v-deep .el-dialog__body {
  padding: 0 20px 5px 20px;
}
::v-deep .el-card__body {
  padding: 10px 10px 10px 10px;
}
</style>